package com.haoshuang.zhouzhoubang.base

import com.mufeng.libs.base.BaseViewModel
import com.mufeng.libs.net.code
import com.mufeng.libs.net.msg
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onStart
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toFlowResponse
suspend fun BaseViewModel.okRequest(
    url: String,
    vararg params: Pair<String, Any?>,
    onStart: () -> Unit = {},
    onSuccess: () -> Unit = {},
    onError: (code: String, msg: String) -> Unit
) : Any{
    return RxHttp.postForm(url)
        .addAll(params.toMap())
        .toFlowResponse<Any>()
        .onStart { onStart() }
        .catch {
            val msg = it.msg
            val code = it.code
            onError(code, msg)
        }.collect {
            onSuccess()
        }
}
suspend inline fun <reified T : Any> BaseViewModel.request(
    url: String,
    vararg params: Pair<String, Any?>,
    crossinline onStart: () -> Unit,
    crossinline onSuccess: (data: T?) -> Unit,
    crossinline onError: (code: String, msg: String) -> Unit
) {

    RxHttp.postForm(url)
        .addAll(params.toMap())
        .toFlowResponse<T>()
        .onStart { onStart() }
        .catch {
            val msg = it.msg
            val code = it.code
            onError(code, msg)
        }.collect {
            onSuccess(it.data)
        }
}